#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
    Setting Module here.

"""
import time, sys, json
import urllib2, thread
from util import *
import config

def getseedlist():
    req = httprequest.openurl(
            'http://www.kaixin001.com/!house/!garden/seedlist.php',{'verify':gardenVerify()[0]})
    r = ET.fromstring(req['data'])
    seedlist = []
    if r.find('ret').text == 'succ':
        for elm in r.findall('seed/item'):
            seedlist.append({elm.find('name').text:elm.find('seedid').text})
    else:
        return False
    return seedlist

def genseedxml():
    verify = gardenVerify()[0]
    idlist = getseedlist()
    listxml = ET.Element('data')
    childlist = ['name', 'rank', 'mhours', 'price', 'fruit_minnum', 
            'fruit_maxnum', 'fruitprice', 'antistealdays','notsteal'
            ]
    ET.SubElement(listxml, 'timestamp').text = time.strftime('%y/%m/%d %H:%M:%S')

    for item in idlist:
        id = item.values()[0]
        req = httprequest.openurl(
                'http://www.kaixin001.com/house/garden/seedinfo.php',
                {'verify':verify,'seedid':id}
                )
        r = ET.fromstring(req['data'])
        item = ET.SubElement(listxml, 'item')
        ET.SubElement(item, 'seedid').text = id
        for child in item:
            print child.tag, child.text
        for i in childlist:
            for element in r.findall(i):
                ET.SubElement(item, element.tag).text = element.text
        profit = ((float(item.find('fruit_minnum').text)+float(item.find('fruit_maxnum').text))/2*float(item.find('fruitprice').text)-float(item.find('price').text))/float(item.find('mhours').text)
        ET.SubElement(item, 'profit_perhour').text = str(round(profit,1))
    ET.ElementTree(listxml).write('seed.xml', encoding='UTF-8')
    

def writeseedlist():
    idlist = getseedlist()
    listxml = ET.Element('data')
    ET.SubElement(listxml, 'timestamp').text = time.strftime('%y/%m/%d %H:%M:%S')

    for item in idlist:
        name = item.keys()[0]
        id = item.values()[0]
        item = ET.SubElement(listxml, 'item')
        ET.SubElement(item, 'name').text = name
        ET.SubElement(item, 'id').text = id
    print ET.tostring(listxml, encoding='UTF-8')
    ET.ElementTree(listxml).write('seedid.xml', encoding='UTF-8')


account = accountInfo()
print account.login('chrisqian@gmail.com')
#writeseedlist()
genseedxml()

